import { defineComponent, reactive, onMounted, ref } from 'vue'
// import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElButton, ElCard, ElSpace, ElLink, ElImageViewer } from 'element-plus'

import type {
  InfoType,
  PramsaType,
  ListType,
  mapViewPropsType,
  TourTaskInfoPropsType
} from './typings'

import styles from './index.module.scss'
import AliIcon from '~/components/AliIocn'
import MapView from './../plan/map'

export default defineComponent({
  name: 'TourTaskInfo',
  props: ['id', 'goBack'],
  setup(props: TourTaskInfoPropsType) {
    const store = useStore()
    // const router = useRouter()
    const info = reactive<InfoType>({})
    const previewFileUrl = ref<string>()
    const params = reactive<PramsaType>({
      // taskId: router.currentRoute.value.query.id,
      taskId: props.id,
      current: 1,
      size: 5000
    })
    const mapData = reactive<mapViewPropsType>({
      id: 'taskUpdateMapr',
      markers: []
    })
    const list = reactive<PramsaType>({
      records: []
    })
    onMounted(() => {
      index()
      listAjax()
    })
    //  初始化数据
    const index = async () => {
      // const id = router.currentRoute.value.query.id
      const { id } = props
      const array: { id: any; latitude: any; longitude: any }[] = []
      const { code, data } = await store.dispatch('tour/PatrolTaskView', { id })
      if (code === 200) {
        info.leadUserName = data.leadUserName
        info.completeStatus = data.completeStatus
        info.beginTime = data.beginTime
        info.endTime = data.endTime
        info.groupName = data.groupName
        info.patrolAssets = data.patrolAssets

        if (data.patrolTaskDetailVOList.length > 0) {
          data.patrolTaskDetailVOList.forEach((item: any) => {
            const lnglta = JSON.parse(item.phase)
            array.push({
              id: item.id,
              longitude: lnglta.coordinates[0],
              latitude: lnglta.coordinates[1]
            })
          })
          mapData.markers = array
        } else {
          mapData.markers = []
        }
      }
    }
    //  巡视记录
    const listAjax = async () => {
      const { code, data } = await store.dispatch('tour/GetPatrolRecordList', params)
      if (code === 200) {
        data.records.forEach((item: ListType, itemIndex: number) => {
          item.isShow = false
          item.info = {}
          const num =
            data.size * Math.ceil(data.total / data.size) -
            (data.size - (data.total % data.size)) -
            itemIndex
          item.num = num
        })
        list.records = data.records
        params.total = data.total
      }
    }
    //  分页
    // const onCurrent = (value: any) => {
    //   params.current = value
    //   listAjax()
    // }
    //  是否显示
    const infoShow = (row: ListType) => {
      row.isShow = !row.isShow
      if (row.isShow) {
        infoAjax(row.id)
      }
    }
    //  请求详情
    const infoAjax = async (id: any) => {
      const { code, data } = await store.dispatch('tour/PatrolRecordView', { id })
      if (code === 200) {
        list.records?.forEach((item: ListType) => {
          if (item.id === id) {
            item.info = data
          }
        })
      }
    }
    //  跳转到工单详情
    const orderOpen = (id: string) => {
      // router.push({ path: '/oam/orderManage/options', query: { id } })
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/oam/orderManage',
        query: { id }
      })
    }
    //  跳转到巡视记录详情
    const infoRecord = (row: any) => {
      // router.push({ path: '/oam/tour/record/info', query: { id: row?.id } })
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/oam/tour/record',
        query: { id: row?.id }
      })
    }
    //  返回
    const goBack = () => {
      // router.go(-1)
      props.goBack!()
    }
    //  点击放大图片
    const handlePreviewFile = (file: string | undefined) => {
      previewFileUrl.value = file
    }
    //  状态转换
    const status = (value: any) => {
      switch (value) {
        case 0:
          return '未开始'
          break
        case 1:
          return '进行中'
          break
        case 2:
          return '已完成'
          break
        case 3:
          return '已超时'
          break
      }
    }

    return () => {
      return (
        <ElCard class={styles['compile-card']}>
          <ElSpace class={styles['compile-tab-option-btns']}>
            <ElButton link type="primary" onClick={goBack}>
              返回上一级&nbsp;
              <AliIcon type="icon-fanhuishangyiji" />
            </ElButton>
          </ElSpace>
          <div class={styles.form}>
            <div class={styles.form_con}>
              <div class={styles.form_con_l}>
                <div class={styles.form_map}>
                  <MapView id={mapData.id} setFitView isMarkers markers={mapData.markers} />
                </div>
                <div class={styles.info}>
                  <div class={styles.info_item}>
                    <div class={styles.label}>责任人</div>
                    <div class={styles.text}>{info.leadUserName}</div>
                  </div>
                  <div class={styles.info_item}>
                    <div class={styles.label}>完成情况</div>
                    <div class={styles.text}>{status(info.completeStatus)}</div>
                  </div>
                  <div class={styles.info_item}>
                    <div class={styles.label}>计划开始时间</div>
                    <div class={styles.text}>{info.beginTime}</div>
                  </div>
                  <div class={styles.info_item}>
                    <div class={styles.label}>计划结束时间</div>
                    <div class={styles.text}>{info.endTime}</div>
                  </div>
                  <div class={styles.info_item} style="width: 100%;">
                    <div class={styles.label}>巡视分组名称</div>
                    <div class={styles.text}>{info.groupName}</div>
                  </div>
                  <div class={styles.info_item} style="width: 100%;">
                    <div class={styles.label}>巡视台区</div>
                    <div class={styles.text} style="color:#3B5EFD;">
                      {info.patrolAssets}
                    </div>
                  </div>
                </div>
              </div>
              <div class={styles.form_item}>
                <ul class={styles.form_item_list}>
                  {list.records?.map((item: ListType) => (
                    <li class={styles.form_item_list_item}>
                      {!item.isShow ? (
                        <div class={styles.form_item_list_ioc} onClick={() => infoShow(item)}>
                          <AliIcon type="icon-shouqi" />
                        </div>
                      ) : (
                        <div
                          class={styles.form_item_list_ioc}
                          style="background: #BDC1CB;"
                          onClick={() => infoShow(item)}
                        >
                          <AliIcon type="icon-xiala" />
                        </div>
                      )}
                      <div class={styles.title}>
                        <div class={styles.label}>第{item.num}次巡视</div>
                        {item.resultState === 2 ? (
                          <div class={styles.status1}>发现缺陷</div>
                        ) : (
                          <div class={styles.status2}>正常</div>
                        )}
                      </div>
                      <div class={styles.contens}>
                        <div class={styles.contens_item}>
                          <div class={styles.label}>巡视人 &nbsp;&nbsp;{item.leadUserName}</div>
                          <div class={styles.time}>
                            巡视时间 &nbsp;&nbsp;{item.beginTime} - {item.endTime}
                          </div>
                        </div>
                      </div>
                      {item.isShow && (
                        <div style="position: relative;">
                          <div class={styles.inforecord} onClick={() => infoRecord(item)}>
                            查看巡视记录
                          </div>
                          <div class={styles.images}>
                            <div class={styles.label}>附件</div>
                            <div class={styles.image}>
                              {item.info.patrolRecordImageVOList?.map((row: any) => (
                                <img
                                  src={row.imageUrl}
                                  onClick={() => handlePreviewFile(row.imageUrl)}
                                  alt=""
                                />
                              ))}
                            </div>
                          </div>
                          <div class={styles.order}>关联工单（{item.info.orderVOList.length}）</div>
                          <ul class={styles.order_list}>
                            {item.info.orderVOList?.map((val: any) => (
                              <li>
                                <div class={styles.order_list_content}>{val.content}</div>
                                <ElLink
                                  type="primary"
                                  style="font-size: 14px;"
                                  onClick={() => orderOpen(val.orderId)}
                                >
                                  查看详情
                                </ElLink>
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}
                    </li>
                  ))}
                </ul>
                {/* {list.records && (
                  <ElPagination
                    v-model:currentPage={params.current}
                    v-model:pageSize={params.size}
                    total={params.total}
                    onCurrent-change={onCurrent}
                    layout="prev, pager, next"
                  />
                )} */}
              </div>
            </div>
          </div>
          {!!previewFileUrl.value && (
            <ElImageViewer
              teleported
              urlList={[previewFileUrl.value]}
              onClose={() => {
                previewFileUrl.value = undefined
              }}
            />
          )}
        </ElCard>
      )
    }
  }
})
